﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ADNDNetwork.Netowork.MessageContainer
{
    public class MessageBus : IMessageBus 
    {
        private static MessageBus mb;

        private List<DNDMessage> messages;
        private List<DNDMessage> receivedMessages;

        private MessageBus()
        {
            messages = new List<DNDMessage>();
            receivedMessages = new List<DNDMessage>();
        }

        public static MessageBus GetInstance()
        {
            if (mb == null)
                MessageBus.mb = new MessageBus();

            return mb;    
        }


        #region IMessageBus Members

        public void ReceiveMessage(DNDMessage m)
        {
            lock (receivedMessages)
            {
                receivedMessages.Add(m);
            }
        }

        public void SendMessage(DNDMessage m)
        {
            lock (mb)
            {
                mb.messages.Add(m);
            }
        }

        public void EmptyMessageQueue()
        {
            lock (messages)
            {
                messages.Clear();
            }
        }

        public void EmptyReceivedMessageQueue()
        {
            lock (receivedMessages)
            {
                receivedMessages.Clear();
            }
        }

        public DNDMessage GetLatestMessage()
        {
            DNDMessage d = null;

            if (messages.Count == 0)
                return null;

            lock (messages)
            {
                d = messages[messages.Count - 1];
            }
            return d;
        }

        public DNDMessage GetLatestReceivedMessage()
        {
            DNDMessage d = null;

            if (receivedMessages.Count == 0)
                return null;

            lock (messages)
            {
                d = receivedMessages[receivedMessages.Count - 1];
            }
            return d;
        }

        #endregion
    }
}
